package cn.com.wxd.action.user;

import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.wxd.action.AjaxResult;
import cn.com.wxd.action.ValidatorResult;
import cn.com.wxd.biz.user.UsersService;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.util.RequestUtil;
import cn.com.wxd.util.action.AccessLogUtil;
import cn.com.wxd.util.action.RequestNotifyUtil;
import cn.com.wxd.util.service.ProjectInfo;
import cn.com.wxd.util.user.UserCoreUtil;

/**
 * Title:用户action
 * Description:处理关于用户的一些请求，如注册和登陆等
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created by ComXu on 2017/5/19.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("")
public class UserCtl {
    private static final Logger log = LoggerFactory.getLogger(UserCtl.class);

    @Resource
    private UsersService usersService;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("/login")
    public String login() {
        return "/user/login";
    }

    /**
     * 注册页面
     *
     * @return
     */
    @RequestMapping("/regist")
    public String regist() {
        return "/user/regist";
    }

    /**
     * ajax登录请求处理
     *
     * @return
     */
    @RequestMapping(value = "/user/ajaxLogin", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult ajaxLogin(HttpServletRequest request, String userName, String passWord, String verCode) {
        ValidatorResult valires = UserCtlValidator.ajaxLoginValidator(request, userName, passWord, verCode);
        if (!valires.isSuccess()) {
            return AjaxResult.failureResult(valires.getMessage());
        }
        if (!usersService.login(request, userName, passWord)) {
            return AjaxResult.failureResult("用户名或密码错误!");
        }
        log.debug(userName + "上线了！");
        return AjaxResult.successResult();
    }

    /**
     * Ajax 注销
     * @param request
     * @return
     */
    @RequestMapping("/user/ajaxLogout")
    @ResponseBody
    public AjaxResult ajaxLogOut(HttpServletRequest request) {
        Object o = UserCoreUtil.getLoginAccount(request);
        if (o != null) {
            //添加到日志
            AccessLogUtil.addUserOperationLog(request, "LOGOUT");
            UserCoreUtil.logoutUser(request);
            //ServletActionContext.getRequest().getSession().invalidate();  //清空session
        }
        return AjaxResult.successResult("注销成功");
    }

    /**
     * 注销
     *
     * @param request
     *
     * @return
     */
    @RequestMapping("/user/logout")
    public String logOut(HttpServletRequest request){
        Object o = UserCoreUtil.getLoginAccount(request);
        if (o != null) {
            //添加到日志
            AccessLogUtil.addUserOperationLog(request, "LOGOUT");
            UserCoreUtil.logoutUser(request);
            //ServletActionContext.getRequest().getSession().invalidate();  //清空session
        }
        return "redirect:/";
    }

    @RequestMapping(value = "/user/ajaxRegist", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult ajaxRegist(HttpServletRequest request, String userName, String nickName, String registType,
                                 String password,
                                 String rePassword, String verCode, String verPhone, String verEmail) {
        ValidatorResult valires = UserCtlValidator.ajaxRegistValidator(request, userName,
                password, rePassword, verCode, registType, verPhone, verEmail);
        if (!valires.isSuccess()) {
            return AjaxResult.failureResult(valires.getMessage());
        }
        AccountInfo accountInfo = new AccountInfo();
        UsersInfo users = new UsersInfo();
        String ip = RequestUtil.getRemortIP(request);
        accountInfo.setUserName(userName);
        accountInfo.setLalogIp(ip);
        String time = DateUtil.getDatetimeStr();
        accountInfo.setLalogTime(time);
        accountInfo.setCreateTime(time);
        users.setPassWord(password); //设置密码
        users.setCreateTime(time);
        users.setIsDisabled("N"); //账号不禁用
        users.setUserType("ORDINARY"); //普通用户
        if (CharUtil.isEmpty(nickName)) {
            users.setNickName(CharUtil.subStringByte(registType + "_" + userName, 12));
        } else {
            users.setNickName(nickName);
        }
        if (registType.equalsIgnoreCase("phone")) {
            accountInfo.setType("PHONE");
            users.setPhone(userName); //设置了手机号
        }
        if (registType.equalsIgnoreCase("email")) {
            accountInfo.setType("EMAIL");
            users.setEmail(userName);  //设置了邮箱
        }

        if (usersService.queryUserB(userName)) {
            return AjaxResult.failureResult("用户已经存在，请输入新的用户名!");
        }

        accountInfo.setUsersInfo(users);

        if (!usersService.addUser(accountInfo)) {
            return AjaxResult.failureResult("未知错误，用户注册失败!");
        }
        accountInfo = usersService.queryAccount(userName);
        if (accountInfo != null) {
            UserCoreUtil.setLoginUser(request, accountInfo);
            AccessLogUtil.addUserOperationLog(request, "REGESTSUCCESS");
            //用户注册成功
            if (log.isDebugEnabled()) {
                log.debug(userName + accountInfo.getUsersInfo().getNickName() + "上线了！");
            }
        }
        if (registType.equalsIgnoreCase("phone")) {
            //清除上次发送短信的时间戳防止检测到连续发
            request.getSession().removeAttribute("verephone" + userName);
        }
        if (registType.equalsIgnoreCase("email")) {
            //清除上次发送邮件的时间戳防止检测到连续发
            request.getSession().removeAttribute("veremail" + userName);
        }
        return AjaxResult.successResult();
    }

    /**
     * 发送注册时的验证码
     */
    @RequestMapping("/user/dynamicPhonecode/regist")
    @ResponseBody
    public AjaxResult sentDynamicPhoneCode(HttpServletRequest request, String userName, String verCode) {
        String sentphone = "";
        if (userName != null) {
            sentphone = userName;
        }
        if (CharUtil.isEmpty(verCode)) {
            return AjaxResult.failureResult("图片验证码不正确");
        }
        String verCodesession = (String) request.getSession().getAttribute("vercode");
        if (verCodesession == null) {
            verCodesession = "";
        }
        if (!verCodesession.equalsIgnoreCase(verCode.trim())) {
            return AjaxResult.failureResult("图片验证码不正确");
        } else {
            if (usersService.queryUserB(userName)) {
                return AjaxResult.failureResult("手机号码已经被占用");
            }
            HashMap<String, String> data = new HashMap<>();
            String randCode = CharUtil.getRanNumber(6);
            data.put("code", randCode);
            data.put("projectName", ProjectInfo.getCompanyName());
            RequestNotifyUtil requestNotifyUtil = new RequestNotifyUtil(request);
            AjaxResult re = requestNotifyUtil.sentSMS(sentphone, data, "userregistsmscode");   //发送短信
            if (re.getErrNo() == 0) {
                request.getSession().setAttribute("USERREG-CODE", randCode);
            } else {
                return re;
            }
        }
        return AjaxResult.successResult();
    }

    /**
     * 注册时发送邮箱动态验证码!
     */
    @RequestMapping("/user/dynamicEmailcode/regist")
    @ResponseBody
    public AjaxResult sentDynamicEmialCode(HttpServletRequest request, String userName, String verCode) {
        String sentemail = "";
        if (userName != null) {
            sentemail = userName;
        }
        if (verCode == null || verCode .equals("")) {
            return AjaxResult.failureResult("图片验证码错误");
        }
        String verCodesession = (String) request.getSession().getAttribute("vercode");
        if (verCodesession == null) {
            verCodesession = "";
        }
        if (!verCodesession.equalsIgnoreCase(verCode.trim())) {
            return AjaxResult.failureResult("图片验证码错误");
        } else {
            if (usersService.queryUserB(userName)) {
                return AjaxResult.failureResult("邮箱已经被占用");
            }
            String randCode = CharUtil.getRanNumber(6);
            HashMap<String, String> map = new HashMap<>();
            map.put("projectName", ProjectInfo.getCompanyName());
            map.put("dateTime", DateUtil.getDateStr());
            map.put("code", randCode);
            RequestNotifyUtil requestNotifyUtil = new RequestNotifyUtil(request);
            AjaxResult re = requestNotifyUtil.sentEmail(sentemail, "用户注册" + ProjectInfo.getCompanyName() +
                            "邮件", map,
                    "userregistemailcode");
            //发送邮件
            if (re.getErrNo() == 0) {
                request.getSession().setAttribute("USERREG-CODE", randCode);
            } else {
                return re;
            }
        }
        return AjaxResult.successResult();
    }

    @InitBinder("users")
    public void initUsers(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("users.");
    }
}
